package com.yy.web.pm.user.service.Impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yy.web.pm.user.Dto.UserLoginDto;
import com.yy.web.pm.user.Dto.UserLoginVO;
import com.yy.web.pm.user.domain.User;
import com.yy.web.pm.user.mapper.UserMapper;
import com.yy.web.pm.user.service.UserService;
import com.yy.web.pm.user.until.HttpClientUtil;
import com.yy.web.pm.until.JwtUtils;
import com.yy.web.pm.until.UserNotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
@Primary
class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Value("${wechat_login_url}")
    private  String WECHAT_LOGIN_URL;
    @Value("${accessToken}")
    private String ACCESSTOKENURL;
    @Value("${phoneURl}")
    private String PHONEURL;
    @Value("${app.id}")
    private String APPID;
    @Value("${app.secret}")
    private String APPSECRET;

    @Override
    public int deleteByPrimaryKey(Long id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(User record) {
        return userMapper.insert(record);
    }

    @Override
    public int insertSelective(User record) {
        return userMapper.insertSelective(record);
    }

    @Override
    public User selectByPrimaryKey(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(User record) {
        return userMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(User record) {
        return userMapper.updateByPrimaryKey(record);
    }

    @Override
    public UserLoginVO authWechat(String code) {
        // 获取 openid
        String openId = getOpenId(code);
        // 查询用户是否已存在
        log.info("当前的openId是{}", openId);
        System.err.println("现在的openId是" + openId);
        User userId = userMapper.getUserByOpenId(openId);
        // 如果用户表没有，则没有进行注册过
        if (userId != null) {
            // 生成JWT
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("openId", openId);
            claims.put("status",userId.getStatus());
            // String token = JwtUtils.genToken(claims);
            String token = JwtUtils.generateToken(String.valueOf(claims));
            return UserLoginVO.builder().id(userId.getId()).username(userId.getUsername()).phone(userId.getPhone()).role(userId.getRoleType()).unit(userId.getUnit()).auditStatus(userId.getAuditStatus()).token(token).build();
        }else {
            throw new UserNotFoundException("用户不存在!");
        }
    }

    /**
     * @ClassName: UserServiceImpl
     * @Description: 类描述:用户注册接口，用户使用手机号进行注册
     * @date: 2025/4/11
     */

    @Override
    public int Userregister(UserLoginDto userLoginDto) {
        // 获取access_token
        String accessToken = getAccessToken();
        // 获取用户手机号
        String phone = getUserPhone(accessToken, userLoginDto.getPhoneCode());
        // 获取用户的OpenID
        String openId1 = getOpenId(userLoginDto.getLoginCode());
        //新增用户
        return insertUser(phone,openId1,userLoginDto);
    }

    @Override
    public User findByOpenid(String openid) {
        return userMapper.selectOpenId(openid);
    }
//查询用户列表
    @Override
    public List<User> selectAll(User user) {
        return userMapper.selectAll(user);
    }

    private int insertUser(String phone,String openId,UserLoginDto userLoginDto) {
        User userByOpenId = userMapper.getUserByOpenId(openId);
        if (userByOpenId == null) {
            User user = new User();
            user.setOpenid(openId);
            user.setUsername(userLoginDto.getUserName());
            user.setPhone(phone);
            user.setRoleType(userLoginDto.getRole());
            user.setStatus("0");//默认未激活
            user.setAuditStatus("2");//默认申请中
            user.setCreatedAt(new Date());
            user.setUnit(userLoginDto.getUnit());
            return userMapper.insert(user);
        }else if (userByOpenId.getAuditStatus().equals("3")){
            User user = new User();
            user.setOpenid(openId);
            user.setUsername(userLoginDto.getUserName());
            user.setPhone(phone);
            user.setRoleType(userLoginDto.getRole());
            user.setStatus("0");//默认未激活
            user.setAuditStatus("4");//重新申请
            user.setId(userByOpenId.getId());
            return userMapper.updateByPrimaryKeySelective(user);
        }
        throw new UserNotFoundException("用户已存在");

    }

    /**
     * @param accessToken:
     * @Title:getUserPhone
     * @Description: 方法描述:获取用户手机号用于注册
     */

    private String getUserPhone(String accessToken, String code) {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", code);
        try {
            System.err.println(PHONEURL + "?access_token=" + accessToken);
            String json = HttpClientUtil.doPost(PHONEURL + "?access_token=" + accessToken, map);
            JSONObject parsed = JSONObject.parseObject(json);
            System.out.println("我们获取到的数据是"+parsed.toString());
            JSONObject phoneInfo = parsed.getJSONObject("phone_info");
            System.out.println("当前我们获取到的数据是"+phoneInfo.toString());
            // 判断手机号是否存在
            if (phoneInfo.getString("phoneNumber")== null){
                System.out.println("错误信息是"+parsed.getString("errcode"));
                throw new UserNotFoundException("错误信息是"+parsed.getString("errcode"));
            }
            String phoneNumber = phoneInfo.getString("phoneNumber");
            return phoneNumber;
        } catch (IOException e) {
            log.error("当前我们的请求是{}，现在我的accessToken是{},我的code是{}", PHONEURL + accessToken, accessToken, code);
            throw new RuntimeException("请求出错了");
        }


    }

    /**
     * @Title:getAccessToken
     * @Description: 方法描述:获取AccessToken
     */
    private String getAccessToken() {
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", APPID);
        map.put("secret", APPSECRET);
        map.put("grant_type", "client_credential");
        //请求发送
        String json = HttpClientUtil.doGet(ACCESSTOKENURL, map);
        // Json转换
        JSONObject jsonObject = JSONObject.parseObject(json);
        // 获取access_token并且返回
        return jsonObject.getString("access_token");
    }

    private String getOpenId(String code) {
        // 添加参数
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", APPID);
        map.put("secret", APPSECRET);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        // 使用封装好的HttpClientUtil工具类发送请求
        String json = HttpClientUtil.doGet(WECHAT_LOGIN_URL, map);
        // 将JSON字符串转换为JSONObject对象
        JSONObject jsonObject = JSON.parseObject(json);
        // 从JSONObject中获取openid并返回
        return jsonObject.getString("openid");
    }
}



